package org.laobai.cart.service;

import org.laobai.cart.entity.Cart;
import org.laobai.common.struct.Result;
import org.laobai.goods.cilent.GoodsClient;
import org.laobai.goods.entity.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;

@Service
public class CartService {

    @Autowired
    private GoodsClient goodsClient;
    @Autowired
    private RedisTemplate redisTemplate;
    private final String KEY_PREFIX = "cart_";

    public boolean addCart(Long goodsId, Integer num) {
        //TODO userId 1L
        // 获取绑定
        BoundHashOperations ops = redisTemplate.boundHashOps(KEY_PREFIX + 1);

        //如果存在
        if(ops.hasKey(goodsId)){
//            ops.putIfAbsent()
            Integer numFormDB = (Integer) ops.get(goodsId);
            ops.put(goodsId,num+numFormDB);
        }else {
            ops.put(goodsId,num);
        }

        return true;
    }

    public List<Cart> list() {
        List<Cart> result = new ArrayList<>();
        // 绑定key
        BoundHashOperations ops = redisTemplate.boundHashOps(KEY_PREFIX + 1);
        // 一组goodsId
        Set<Long> keys = ops.keys();
        // 商品
        List<Goods> goods = goodsClient.getByIds(keys);

        Supplier<Cart> supplier = new Supplier<Cart>() {
            @Override
            public Cart get() {
                return new Cart();
            }
        };


        goods.forEach(item->{
            Cart cart = supplier.get();
            cart.setGoods(item);

            cart.setNum((Integer) ops.get(item.getId()));

            result.add(cart);
        });

        return result;
    }
}
